package tt.dz.order.util.page;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;

import tt.dz.order.dao.BaseDAOUtil;

/**
 * 默认的分页构造器实现
 * 
 * @author anson-worker
 *
 * @param <T>
 */
public class DefaultPaginationBuilder implements PaginationBuilder {

	private static final String QUERY_SQL_FMT = "    %s offset %d   limit %d ";

	/**
	 * sql业务呈现的列表sql
	 */
	private String countSql;

	/**
	 * sql业务逻辑控制sql
	 */
	private String businessSql;

	private Map<String, Object> params;

	private int currentPageNo;

	private int prePageSize;

	public DefaultPaginationBuilder() {
		super();
	}

	@Override
	public void doBusiness(String countSql, String businessSql, Map<String, Object> params) {
		this.countSql = countSql;
		this.businessSql = businessSql;
		this.params = params;
	}

	@Override
	public void doPagination(int currentPageNo, int prePageSize) {
		this.currentPageNo = currentPageNo;
		this.prePageSize = prePageSize;
	}

	/**
	 * 计算当前业务逻辑的总条数
	 * 
	 * @return
	 */
	private int count() {
		Integer t = BaseDAOUtil.execute(this.countSql, this.params, new PreparedStatementCallback<Integer>() {
			@Override
			public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
				Integer count = 0;
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					count = rs.getInt(1);
				}
				return count;
			}
		});
		return t == null ? 0 : t.intValue();
	}

	private <T> List<T> query(Class<T> clazz, int nextItemStartNo, int pageSize) {
		List<T> list = null;
		String sql = String.format(QUERY_SQL_FMT, this.businessSql, nextItemStartNo, pageSize);
		list = BaseDAOUtil.queryForList(sql, params, clazz);
		return list;
	}

	@Override
	public <T> Pagination<T> product(Class<T> clazz) {
		Pagination<T> pagination = new Pagination<T>();
		pagination.setCurrentPage(this.currentPageNo);
		pagination.setPageSize(this.prePageSize);
		// 所有的记录条数
		int allRow = this.count();
		// 当前开始的记录点
		int nextItemStartNo = pagination.countOffset();
		// 查询条数处理
		List<T> list = this.query(clazz, nextItemStartNo, pagination.getPageSize());
		pagination.setAllRow(allRow);
		pagination.setList(list);
		pagination.dealPage();
		return pagination;
	}

}
